package com.jms.service.task.impl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;

import com.jms.dao.BaseDaoI;
import com.jms.model.cms.Tnews;
import com.jms.model.sys.Tplan;
import com.jms.pageModel.cms.News;
import com.jms.service.task.TaskServiceI;
import com.jms.utils.CreateHTML;
import com.jms.utils.StringUtil;

@Service
public class TaskServiceImpl implements TaskServiceI,ServletContextAware{
	private ServletContext servletContext;
	@Autowired
	private BaseDaoI<Tplan> planDao;
	@Autowired
	private BaseDaoI<Tnews> newsDao;
	
	@Override
	public void run() {
		System.out.println("定时任务执行...");
		String hql = " from Tplan t ";
		List<Tplan> l = planDao.find(hql);
		Iterator<Tplan> it = l.iterator();
		while(it.hasNext()){
			Tplan t = it.next();
			
			if(t.getController()!=null&&"createHTML".equals(t.getController())){
				createHTML(t.getAction());
				
			}
		}
	}

	@Override
	public void createHTML(String action) {
			if(action!=null&&"article_detail".equals(action)){
				try {
				String hql = " from Tnews t ";
				List<Tnews> l = newsDao.find(hql);
				Iterator<Tnews> it = l.iterator();
				CreateHTML chtml = new CreateHTML();
				while(it.hasNext()){
					Tnews t = it.next();
					if(t.getStatus()!=null&&t.getStatus()==1){
						
						News news = new News();
						StringUtil.beanCopy(t, news, false);
						//生成静态html开始
						Map root = new HashMap();
						root.put("news", news);
						SimpleDateFormat fymd = new SimpleDateFormat ("yyyy/MM/dd");
						String sDate = fymd.format(t.getPubtime());
						chtml.geneHtmlFile("index.ftl", root, servletContext.getRealPath("/www")+"/"+sDate, t.getId()+".html", servletContext.getRealPath("/WEB-INF/templates"));
						//生成静态html结束
						
						//新闻内容加入静态链接
						String spath = "/news/"+sDate+"/"+t.getId()+".html";
						t.setUrl(spath);
						newsDao.update(t);
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
			}
		}
		
	}
	
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
		
	}
}
